const wrapperEle = document.querySelector('.wrapper')
/**
 * 显示用户信息
 * 1. 从localStorage中获取保存的用户信息
 * 2. 动态渲染页面
 */
function showUser() {
	let user = localStorage.getItem('USER')
	user = JSON.parse(user)

	let headerStr = `<img src="${user.headerimg}" alt="logo">
                    <h3>后台管理中心</h3>
                    <p class="nick">${user.nick}</p>`

	const title = document.querySelector('header>.title')
	title.innerHTML = headerStr
}

/**
 * 退出
 *   1. 清除localStorage登录用户信息
 */
function logout() {
	const logoutBtn = document.querySelector('header>button')
	logoutBtn.addEventListener('click', function () {
		// 1. 清除localStorage登录用户信息
		localStorage.removeItem('USER')
		// 2. 跳转到登录界面
		location.href = './login.html'
	})
}

/**
 *   1. 调用用户列表接口获取用户列表数据
 */
function loadUserList(pageNo) {
	axios({
		method: 'get',
		url: 'http://10.7.173.69:8088/api/list_page',
		//axios库get请求:parmas传参
		//axios库post请求: data传参
		params: {
			pageNo,
		},
	}).then(response => {
		let data = response.data
		if (data.resultCode == 1) {
			let result = data.resultInfo //用户列表数据
			showUserList(result)
		}
	})
}

/**
 * 动态渲染用户列表
 */
function showUserList(result) {
	let str = `<table><tr>
                    <th>序号</th>
                    <th width="150px">头像</th>
                    <th width="200px">姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>操作</th>
                </tr>`

	let arr = result.list.map(item => {
		return `<tr>
                    <td>${item.uid}</td>
                    <td><img src="${item.headerimg}"/></td>
                    <td>${item.username}</td>
                    <td>${item.age}</td>
                    <td>${item.sex == 0 ? '男' : '女'}</td>
                    <td><a href="javascript:void(0)" date-index="${item.uid}" class="del-user">删除</a></td>
                </tr>`
	})
	str = str + arr.join('') + '</table>' + '<div class="m-style m-box"></div>'

	wrapperEle.innerHTML = str

	$('.m-box').pagination({
		// mode:fix,
		coping: true,
		homePage: '首页',
		endPage: '末页',
		prevContent: '上页',
		nextContent: '下页',
		totalData: result.total, // 数据条数
		showData: 5, //每页显示条数
		current: result.currentNo, //当前页
		jump: true, //跳转页
		callback: function (api) {
			console.log(api.getCurrent()) //显示当前页号
			loadUserList(api.getCurrent())
		},
	})
}

/**
 * 删除用户
 * 事件委托
 */
function onDeleteUser() {
	wrapperEle.addEventListener('click', function (e) {
		e = e || window.event
		let target = e.target || e.srcElement
		if (target.getAttribute('class') == 'del-user') {
			let isOk = confirm('确定要删除此记录吗?')
			if (isOk) {
				let id = target.getAttribute('date-index')

				axios({
					method: 'get',
					url: 'http://10.7.173.69:8088/api/delete',
					params: {
						uid: id,
					},
				}).then(function (response) {
					data = response.data
					if (data.resultCode == 1) {
						loadUserList(1)
					}
				})
			}
		}
	})
}

/**
 * 绑定菜单事件
 */
function bindMenu() {
	//用户列表
	const userListEle = document.querySelector('.container .user-list')
	userListEle.addEventListener('click', function () {
		loadUserList(1)
	})
	//添加用户
	const userAddEle = document.querySelector('.container .user-add')
	userAddEle.addEventListener('click', function () {
		showAddUser()
	})

	//轮播效果
	const swiperEle = document.querySelector('.container .swiper-module')
	swiperEle.addEventListener('click', function () {
		loadSwiper()
	})
}

/**
 * 获取轮播数据
 */
function loadSwiper(){
	axios({
		method:'get',
		url:'http://api.yuguoxy.com/api/shop/banner'
	}).then(response=>{
		let data = response.data
		if(data.resultCode == 1){
			let list = data.resultInfo.list
			showSwiper(list)
		}
	})
}

/**
 * 加载轮播页面
 *   1. 下载引入swiper轮播插件css和js
 *   2. html结构
 *   3. css样式
 *   4. 初始化swiper实例
 */
function showSwiper(list) {
	let swiperStr = list.map(item=>{
		return `<div class="swiper-slide"><img src="${item.url}" alt="${item.content}"></div>`
	}).join('')

	let str = `<div class="swiper" style="margin-top:50px;">
					<div class="swiper-wrapper">`+
					swiperStr +
					`</div>
					<div class="swiper-pagination"></div>

					<div class="swiper-button-prev"></div>
					<div class="swiper-button-next"></div>
				</div>`
	wrapperEle.innerHTML = str

	//实例化swiper
	new Swiper('.swiper', {
		autoplay: true, //可选选项，自动滑动
		loop: true, // 循环模式选项
		// 如果需要分页器
		pagination: {
			el: '.swiper-pagination',
			clickable: true,
		},
		// 如果需要前进后退按钮
		navigation: {
			nextEl: '.swiper-button-next',
			prevEl: '.swiper-button-prev',
		},
	})
}

/**
 * 动态渲染添加用户
 */
function showAddUser() {
	let str = `<form class="add-user">
                <input type="text" name="username" placeholder="请输入用户名"><br>
                <input type="text" name="headerimg" placeholder="请输入头像"><br>
                <input type="text" name="age" placeholder="请输入年龄"><br>
                <input type="text" name="sex" placeholder="请输入性别, 0:男1:女"><br>
                <input type="submit" value="添加用户">
              </form>`
	wrapperEle.innerHTML = str

	bindAddUser()
}

/**
 * 绑定添加用户事件
 */
function bindAddUser() {
	const addUserBtn = document.querySelector('.add-user')
	const userInput = document.querySelector('input[name="username"]')
	const headerimgInput = document.querySelector('input[name="headerimg"]')
	const ageInput = document.querySelector('input[name="age"]')
	const sexInput = document.querySelector('input[name="sex"]')

	addUserBtn.addEventListener('submit', function (e) {
		e = e || window.event
		e.preventDefault()

		axios({
			method: 'post',
			url: 'http://10.7.173.69:8088/api/user/add',
			data: {
				username: userInput.value,
				age: ageInput.value,
				headerimg: encodeURIComponent(headerimgInput.value),
				sex: sexInput.value,
			},
		}).then(function (response) {
			let data = response.data
			if (data.resultCode == 1) {
				alert('添加成功')
			} else {
				alert(data.resultInfo)
			}
		})
	})
}

showUser()
logout()
// loadUserList() // 进来显示用户列表打开此注释
bindMenu()
onDeleteUser()
